//
//  KDCollectController.m
//  WangJingApp
//
//  Created by 魏强 on 17/11/6.
//  Copyright © 2017年 KDTech. All rights reserved.
//

#import "KDCollectController.h"
#import "KDChildCollectController.h"
#import "KDCollectRequestTool.h"
#import "KDFavorTypeListResult.h"
#import "KDFavorType.h"
#import "KDTabBarController.h"
@interface KDCollectController ()<UITextFieldDelegate>
/**
 *  所有主题数据的集合
 */
@property (nonatomic, strong) NSArray * themeArr;
/**  右边的加号按钮 */
//@property (nonatomic, strong) UIButton *rightBtn;
/**  收藏夹名称 */
@property (nonatomic, copy) NSString * typeName;
@end

@implementation KDCollectController
#pragma mark - 懒加载区
- (NSArray *)themeArr
{
    if (!_themeArr) {
        _themeArr = [NSArray array] ;
    }
    return _themeArr;
}
#pragma mark - 生命周期区
- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self setupNavBar];
    [self loadData];
    // Do any additional setup after loading the view.
}
#pragma mark - 板块布置区
- (void)setupNavBar{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"collect_add"] style:UIBarButtonItemStylePlain target:self action:@selector(rightItemClick)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"leftArrow"] style:UIBarButtonItemStylePlain target:self action:@selector(leftItemClick)];
    
}
- (void)setupAllChildViewController{
    if (self.childViewControllers.count) {
        for (UIViewController *child in self.childViewControllers) {

            [child removeFromParentViewController];
            [child.view removeFromSuperview];
        }

    }
    for (KDFavorType *model in self.themeArr) {

        KDChildCollectController *child = [[KDChildCollectController alloc]init];
        child.title = model.type_name;
        child.model = model;
        [self addChildViewController:child];
        //        }
    }
    // 4.设置所有标题
    self.needUnderLine = YES;
    [super setupAllTitle];
}
#pragma mark - 事件点击区
/**
 *  添加主题按钮被点击了
 */
- (void)rightItemClick{
    NSString *title = NSLocalizedString(@"新建收藏夹", nil);
    NSString *message = NSLocalizedString(@"请输入收藏夹名称", nil);
    NSString *cancelButtonTitle = NSLocalizedString(@"取消", nil);
    NSString *otherButtonTitle = NSLocalizedString(@"确定", nil);
    ;
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.delegate = self;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTextFieldTextDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:textField];
        
        //        textField.secureTextEntry = YES;
    }];
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:otherButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        //        NSLog(@"The \"Secure Text Entry\" alert's other action occured.");
        [self addCollectType];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:alertController.textFields.firstObject];
        
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        KDLog(@"The \"Secure Text Entry\" alert's cancel action occured.");
        [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:alertController.textFields.firstObject];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:otherAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)leftItemClick{
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 网络请求区
- (void)loadData{
    WS(ws);
    KDBaseParam *param = [[KDBaseParam  alloc]init];
//    param.method = @"collection/type/myCollectionType";
    [KDCollectRequestTool getFavorTypeListWithParam:param success:^(KDFavorTypeListResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            ws.themeArr = responseObejct.data;
            [ws setupAllChildViewController];
        }else if ([responseObejct.code isEqualToString:@"E040110000001"]){
            [self.navigationController dismissViewControllerAnimated:NO completion:^{
                KDNewfeatureController *new = [[KDNewfeatureController alloc]init];
                __block KDTabBarController*ctr = (KDTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                [UIApplication sharedApplication].keyWindow.rootViewController = new;
                [ctr removeObserver];
                [ctr removeFromParentViewController];
                ctr = nil;
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误!" maskType:SVProgressHUDMaskTypeGradient];
    }];
}

/**
 *  添加收藏夹的请求
 */
- (void)addCollectType{
    if (!self.typeName) {
        [SVProgressHUD showErrorWithStatus:@"未输入" maskType:SVProgressHUDMaskTypeGradient];
        return;
    }
    NSDictionary *dic = @{@"type_name":self.typeName};
    WS(ws);
    [KDCollectRequestTool addFavorTypeWithParam:dic success:^(KDBaseResult *responseObejct) {
        if ([responseObejct.code isEqualToString:@"1"]) {
            KDFavorType *type = [KDFavorType objectWithKeyValues:responseObejct.data];
            NSMutableArray *arr = [NSMutableArray arrayWithArray:ws.themeArr];
            [arr insertObject:type atIndex:0];
            ws.themeArr = arr;
            [ws setupAllChildViewController];
            //            [ws.presentedViewController dismissViewControllerAnimated:NO completion:nil];
        }else{
            [SVProgressHUD showErrorWithStatus:responseObejct.msg maskType:SVProgressHUDMaskTypeGradient];
        }
        [ws.presentedViewController dismissViewControllerAnimated:NO completion:nil];
        
    } failure:^(NSError *error) {
        [ws.presentedViewController dismissViewControllerAnimated:YES completion:nil];
        
        [SVProgressHUD showErrorWithStatus:@"网络问题" maskType:SVProgressHUDMaskTypeGradient];
    }];
}
#pragma mark - 通知接收区


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)handleTextFieldTextDidChangeNotification:(NSNotification *)notification {
    UITextField *textField = notification.object;
    self.typeName = textField.text;
}
@end
